package com.example.booksystem.view.page;

import com.example.booksystem.controller.BookController;
import com.example.booksystem.model.Book;
import com.example.booksystem.view.Index;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.ScrollPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

import java.sql.SQLException;
import java.util.List;

public class BorrowBook {
    private static List<Book> books;
    private static VBox data;
    private static Integer id;
    public static void show(Integer userId){
        id = userId;
        getBook();
        showBook();
        Stage stage = new Stage();
        Scene  scene = new Scene(data,1280,720);
        stage.setScene(scene);
        stage.setTitle("借阅图书");
        stage.show();
    }

    private static void getBook() {
        try {
            books = new BookController().selectBorrowBook(id);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    private static void showBook() {
        ScrollPane scrollPane = new ScrollPane();
        scrollPane.setPrefHeight(680);
        scrollPane.setPrefWidth(1200);
        scrollPane.setFitToWidth(true);
        VBox bookList = new VBox();
        for (int i = 0; i < books.size(); i++) {
            HBox hBox = new HBox();
            hBox.setAlignment(Pos.CENTER);
            Label[] labels = new Label[6];
            labels[0] = new Label(books.get(i).getId());
            labels[1] = new Label(books.get(i).getTitle());
            labels[2] = new Label(books.get(i).getAuthor());
            labels[3] = new Label(books.get(i).getPress());
            labels[4] = new Label(books.get(i).getPrice());
            labels[5] = new Label(String.valueOf(books.get(i).getNum()));
            for (Label label : labels) {
                HBox box = new HBox();
                box.setAlignment(Pos.CENTER);
                box.setPrefWidth(180);
                box.getChildren().add(label);
                hBox.getChildren().add(box);
            }
            bookList.getChildren().add(hBox);
            HBox operate = new HBox();
            operate.setAlignment(Pos.CENTER);
            operate.setPrefWidth(180);
            Button button = new Button("归还");
            Book book = books.get(i);
            button.setOnAction(e->{
                try {
                    if (new BookController().returnBook(id,book.getId())){
                        Index.success("归还成功");
                    }
                } catch (SQLException ex) {
                    throw new RuntimeException(ex);
                }
            });
            operate.getChildren().add(button);
            hBox.getChildren().add(operate);
        }
        scrollPane.setContent(bookList);
        data = new VBox(scrollPane);

    }
}
